package org.example.day11;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 4.1.8.3 实现生产者/消费者 多对对交替打印
 *      ③设置两个condition来解决只唤醒互补线程，从而解决假死
 */
public class MyThread4 {
    private ReentrantLock lock = new ReentrantLock();
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private boolean hasValue = false;
    public void set(){
        try {
            lock.lock();
            while(hasValue == true){
                System.out.println("有可能★★连续");
                conditionA.await();
            }
            System.out.println("打印★");
            hasValue = true;
            conditionB.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void get(){
        try {
            lock.lock();
            while(hasValue == false){
                System.out.println("有可能☆☆连续");
                conditionB.await();
            }
            System.out.println("打印☆");
            hasValue = false;
            conditionA.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        MyThread4 m4 = new MyThread4();
        Thread4A[] tas = new Thread4A[10];
        Thread4B[] tbs = new Thread4B[10];
        for (int i = 0; i < 10; i++) {
            tas[i] = new Thread4A(m4);
            tbs[i] = new Thread4B(m4);
            tas[i].start();
            tbs[i].start();
        }
    }
}

class Thread4A extends Thread{
    private MyThread4 m4;

    public Thread4A(MyThread4 m4) {
        this.m4 = m4;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            m4.set();
        }
    }
}

class Thread4B extends Thread{
    private MyThread4 m4;

    public Thread4B(MyThread4 m4) {
        this.m4 = m4;
    }

    @Override
    public void run() {
        for (int i = 0; i <1000; i++) {
            m4.get();
        }
    }
}
